<?php

namespace app\api\service;

use think\Request;

class ZipService extends Api
{
    protected static $instance;
    protected $zip;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->zip = new \ZipArchive();
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 打包已有的文件
     * @author LH
     * @param $files 打包文件：数组 例：['/uploads/20191017/45b118a92fce2f43a69f82a1e040f525.xls','/uploads/20191017/3887cc37ed30136a4df9304457132593.xls']
     * @param string $zipName
     */
    public function createZip($files,$zipName=''){
        if(empty($zipName)){
            $zipname = datetime(time(),'YmdHis').'.zip';
        }else{
            $zipname = $zipName.'.zip';
        }
        $currentdir = ROOT_PATH . '/public';
        $zipFilePath = '/uploads/zip/'.datetime(time(),'Ymd').'/';
        $zipDir=$currentdir.$zipFilePath;
        $zipPath = mb_convert_encoding($zipDir . $zipname, 'utf-8');
        if (!is_dir($zipDir)) {
            @mkdir($zipDir, 0777, true);
        }
        if (!file_exists($zipPath)) {
            $cc = $this->zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);//创建一个空的zip文件
            if (!empty($files)) foreach ($files as $file) {
                $file = str_replace($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'], '', $file);
                list($path, $ext) = explode('.', $file);
                $path = explode('/', $path);
                $name = end($path) . '.' . $ext;
                $gbkFile = mb_convert_encoding($file, 'utf-8');

                ($this->zip->addFile($currentdir . $gbkFile, $name));
            }

            $this->zip->close();
        }
        return mb_convert_encoding($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$zipFilePath.$zipname, 'utf-8');
//        return mb_convert_encoding($zipPath, 'utf-8');
    }
}